﻿(function ($) {
    "use strict";
    $.jgrid = $.jgrid || {};
    $.extend($.jgrid, {
        click: function ($tr, p, is_click) {
            var id = "";
            var rowobj = {};
            $("#" + p.id).find("thead th").each(function (idx, thobj) {
                var key = thobj.id.slice(p.id.length + 1);
                var val = $tr.find("td:eq(" + idx + ")").text();
                id = idx == (p.multiple ? 1 : 0) ? val : id;
                rowobj[key] = val;
            });

            if (typeof p.onclick == "function" && is_click) {
                p.onclick($tr.data("rowidx"), id, rowobj);
            }
            if (typeof p.ondbclick == "function" && !is_click) {
                p.ondbclick($tr.data("rowidx"), id, rowobj);
            }
        },
        onclick: function ($tr, p) {
            $.jgrid.click($tr, p, true);
        },
        ondbclick: function ($tr, p) {
            $.jgrid.click($tr, p, false);
        },
        load: function (obj, pagenum) {
            var p = obj;
            p.param.pagenum = pagenum;
            p.param.pagesize = p.pagesize;

            $.post(p.url, p.param, function (msg) {
                p.size = msg.size;
                p.page = msg.page;

                var $content = $("tbody", $("#" + p.id)).empty();

                if (msg && msg.rows && msg.rows.length) {

                    for (var i = 0; i < msg.rows.length; i++) {
                        var json = msg.rows[i];
                        var html = "<tr data-rowidx='" + i + "'>";
                        if (p.multiple) {
                            html += "<td align='center'><input type='checkbox' id='grid-" + p.id + "-ckone" + i + "'></td>";
                        }
                        for (var j = 0; j < p.cols.length; j++) {
                            var col = p.cols[j];
                            col.align = col.align ? col.align : "center";
                            col.hidden = col.hidden ? col.hidden : false;
                            var hiddenstyle = col.hidden ? "width:0;display:none" : "";

                            html += "<td align='" + col.align + "' style='" + hiddenstyle + "' >";

                            if (col.formatter) {
                                if (typeof col.formatter === "function") {
                                    html += col.formatter(json);
                                } else {
                                    switch (col.formatter.type) {
                                    case "date":
                                        html += json[col.id].fmtjsondate(col.formatter.fmt);
                                        break;
                                    case "select":
                                        var s = col.formatter.fmt;
                                        for (var k in s) {
                                            if (k.toString() == json[col.id].toString()) {
                                                html += s[k.toString()];
                                                break;
                                            }
                                        }
                                        break;
                                    case "link":
                                        var link = col.formatter.fmt;
                                        var a = link.href;
                                        var arr = link.val.split(',');
                                        for (var l = 0; l < arr.length; l++) {
                                            var re = new RegExp('\\{' + (l) + '\\}', 'gm');
                                            a = a.replace(re, json[arr[l]]);
                                        }
                                        html += a;
                                        break;
                                    default:

                                    }
                                }

                            } else {
                                var v = json[col.id];
                                html += v == null ? "" : v;
                            }

                            html += "</td>";

                        }
                        html += "</tr>";
                        $content.append(html);


                        $content.find("tr:even").addClass("gridevenrow");
                        $content.find("tr").filter(':has(:checkbox:checked)')
                            .addClass('gridselrow')
                            .end()
                            .unbind("click")
                            .unbind("dblclick")
                            .bind("click", function(event) {
                                if (event.target.tagName == "TD") {

                                    var $tr = $(this);

                                    if (p.multiple && event.target.type !== 'checkbox') {
                                        $tr.children("td:first").find(":checkbox").trigger('click');
                                    }
                                    !p.multiple && $.jgrid.onclick($tr, p);

                                    if (p.multiple) {
                                        $tr.toggleClass('gridselrow', $tr.children("td:first").find(":checkbox").get(0).checked);
                                    } else {
                                        $tr.addClass("gridselrow").siblings(".gridselrow").removeClass("gridselrow");
                                    }

                                }
                            })
                            .bind("dblclick", function(event) {
                                $.jgrid.ondbclick($(this), p);
                            });

                        if (p.multiple) {
                            $(":checkbox[id^='grid-" + p.id + "-ckone']").unbind("click").bind("click", function(evt) {
                                if (event.target.type === 'checkbox') {
                                    $(this).parent().parent().toggleClass("gridselrow", this.checked);
                                    $.jgrid.onclick($(this).parent().parent(), p);
                                }
                            });
                        }
                        if (typeof p.onloaded == "function" && (i + 1) == msg.rows.length) {
                            p.onloaded();
                        }
                    }
                } else {
                    if (typeof p.onloaded == "function") {
                        p.onloaded();
                    }
                }

                if (p.multiple) {
                    $("#grid-" + p.id + "-ckall").unbind("click").bind("click", function () {
                        var ckstate = this.checked;
                        if (event.target.type === 'checkbox') {
                            $(":checkbox[id^='grid-" + p.id + "-ckone']").attr("checked", ckstate).prop("checked", ckstate);
                            if (ckstate) {
                                $content.find("tr").addClass("gridselrow");
                            } else {
                                $content.find("tr").removeClass("gridselrow");
                            }

                            if (typeof p.oncheckall == "function") {
                                p.oncheckall(ckstate);
                            }
                        }
                    });
                }

                if (p.pager) {
                    $("#" + p.pager).css("margin", "0").bootstrapPaginator({
                        bootstrapMajorVersion: 3,
                        numberOfPages: 7,
                        currentPage: p.page,
                        totalPages: p.size,
                        alignment: 'left',
                        useBootstrapTooltip: true,
                        tooltipTitles: function (type, page, current) {
                            switch (type) {
                                case "first":
                                    return "首页";
                                case "prev":
                                    return "上一页";
                                case "next":
                                    return "下一页";
                                case "last":
                                    return "末页";
                                case "page":
                                    return current != page ? "前往第" + page + "页" : "第" + page + "页";
                            }
                        },
                        bootstrapTooltipOptions: {
                            html: false,
                            placement: 'top'
                        },
                        itemContainerClass: function (type, page, current) {
                            return (page === current) ? "active" : "pointer-cursor";
                        },
                        onPageClicked: function (e, originalEvent, type, page) {

                        },
                        onPageChanged: function (e, oldPage, newPage) {
                            $.jgrid.load(p, newPage);
                        }
                    });
                }
            });
        },
        getAccessor: function (obj, expr) {
            if (typeof expr === 'function') { return expr(obj); }
            var ret = obj[expr];
            if (ret === undefined) {
                return function () {
                    alert("$.jgrid.getAccessor 没有此方法");
                };
            }
            return ret;
        },
        getMethod: function (name) {
            return this.getAccessor($.fn.bootgrid, name);
        },
        extend: function (methods) {
            $.extend($.fn.bootgrid, methods);
        }
    });


    $.fn.bootgrid = function (pin) {
        if (typeof pin === 'string') {
            var fn = $.jgrid.getMethod(pin);
            if (!fn) {
                throw ("bootgrid - No such method: " + pin);
            }

            var args = $.makeArray(arguments).slice(1);

            //apply函数第一个参数为目标对象（即替换当前对象的对象），第二个参数是一个参数数组或者(arguments)，
            // call函数第一个参数为目标对象（即替换当前对象的对象），第二个参数是参数值（逗号分隔）

            return fn.apply(this, args);
        }

        if (this.size() == 0) {
            alert("未找到grid table！");
            return;
        }

        return this.each(function () {

            if (this.grid) { return; }

            var p = $.extend(true, {
                headers: [],
                cols: [],
                url: "",
                param: {},
                page: 1,
                size: 1,
                pagesize: 30,
                pager: "",
                ondbclick: null,
                onclick: null,
                onloaded: null,
                multiple: false,
                oncheckall: null

            }, pin || {});

            var ts = this, grid = {
                headers: [],
                cols: []
            };
            if (this.tagName.toUpperCase() !== 'TABLE') {
                alert("grid 目标标签不是 table");
                return;
            }
            $(this).empty().addClass("table table-bordered").removeClass("table-hover table-striped");

            p.id = this.id;

            if (p.headers.length === 0) {
                for (var i = 0; i < p.cols.length; i++) {
                    this.p.headers[i] = p.cols[i].label || p.cols[i].name;
                }
            }
            if (p.headers.length !== p.cols.length) {
                alert("headers.length !== cols.length");
                return;
            }

            var thead = "<thead><tr>";

            if (p.multiple) {
                thead += "<th align='center' style='width:30px;'><input type='checkbox' id='grid-" + p.id + "-ckall'></th>";
            }
            for (var i = 0; i < p.headers.length; i++) {
                var col = p.cols[i];
                col.align = col.align ? col.align : "center";
                col.hidden = col.hidden ? col.hidden : false;
                var hiddenstyle = col.hidden ? "width:0;display:none" : "";
                thead += "<th style='text-align:" + col.align + ";" + hiddenstyle + ";' id='" + p.id + "_" + p.cols[i].id + "'>";
                thead += p.headers[i];
                /*   if (!p.cols[i].width) { p.cols[i].width = 150; }
                   else { p.cols[i].width = parseInt(p.cols[i].width, 10); }*/
                thead += "</th>";
            }
            thead += "</tr></thead><tbody></tbody>";
            $(this).append(thead);

            this.p = p;
            this.grid = grid;
            $.jgrid.load(this.p, 1);
        });
    };


    $.jgrid.extend({
        getGridParam: function (pName) {
            var $t = this[0];
            if (!$t || !$t.grid) { return; }
            if (!pName) { return $t.p; }
            return $t.p[pName] !== undefined ? $t.p[pName] : null;
        },
        setGridParam: function (newParams) {
            return this.each(function () {
                if (this.grid && typeof newParams === 'object') { $.extend(true, this.p.param, newParams); }
            });
        },
        reloadGrid: function (params) {
            return this.each(function () {
                var pagenum = params.page;
                this.p.param.pagenum = pagenum;
                $.jgrid.load(this.p, pagenum);
            });
        },
        getGridSelRow: function () {
            var $t = this[0];
            var size = $("tbody tr", $t).size();
            if (size == 0) {
                mainfn.msg("列表无数据！");
                return null;
            }
            var $sel = $("tbody .gridselrow:first", $t);
            if ($sel.size() == 0) {
                mainfn.msg("请先在列表中选择一条记录！");
                return null;
            }
            var rowobj = {};
            $("thead th", $t).each(function (idx, thobj) {
                var key = thobj.id.slice($t.id.length + 1);
                var val = $sel.find("td:eq(" + idx + ")").text();
                rowobj[key] = val;
            });
            return rowobj;
        },
        getGridSelRows: function () {

            if (!this[0].p.multiple) {
                mainfn.msg("错误：本方法需要配置GRID参数[multiple:true]");
                return null;
            }
            var gridid = this[0].id;

            var size = $("tbody tr", this[0]).size();
            if (size == 0) {
                mainfn.msg("列表无数据！");
                return null;
            }
            var $sel = $("tbody .gridselrow", this[0]);

            if ($sel.size() == 0) {
                mainfn.msg("请先在列表中选择一条记录！");
                return null;
            }
            var rets = [];

            var $theadth = $("thead th", this[0]);

            $sel.each(function (idx, tr) {
                var obj = {};
                $theadth.each(function (idxth, thobj) {
                    if (idxth != 0) {
                        var key = thobj.id.slice(gridid.length + 1);
                        var val = $(tr).find("td:eq(" + idxth + ")").text();
                        obj[key] = val;
                    }
                });
                rets.push(obj);
            });
            return rets;
        },
        removeSelRows: function () {
            $("tbody .gridselrow", this[0]).remove();
        }
    });

})(jQuery);